package kata19;

import java.util.*;
import java.util.stream.Collectors;

public class WordChains3 {

    private Set<String> chains;
    private List<String> hasAdd;

    public WordChains3(Set<String> words) {
        chains = words;
        hasAdd = new ArrayList<>();
    } /**
     * 获取近义词
     * @param source
     * @return
     */
    public List<String> getSynonyms(String source){
        List<String> result = new ArrayList<>();
        while (true){
            if(source == null){
                break;
            }
            source = matchSynonyms(source,result);
        }
        return result;
    }

    /**
     * 匹配近义词
     * @param source 源词
     * @param alreadyMatch 已匹配的词
     * @return 匹配的好的词
     */
    public String  matchSynonyms(String source,List<String> alreadyMatch){
        for (String innerStr : chains) {
            if(alreadyMatch.contains(innerStr)){
                //如果已匹配，跳过当次循环
                continue;
            }
            if(innerStr.length() == source.length()){
                char[] innerChars = innerStr.toCharArray();
                char[] wordChars = source.toCharArray();
                int charLength = innerChars.length;
                int alikeCount = 0;
                //字符比较
                for(int i = 0;i < charLength; i++){
                    if(wordChars[i] == innerChars[i]){
                        ++alikeCount;
                    }
                }

                //区别一个字符，则满足条件,
                if((charLength - 1) == alikeCount){
                    //加入匹配队列
                    alreadyMatch.add(innerStr);
                    return innerStr;
                }
            }
        }
        return null;
    }

    public List<String> getMiddleChain (String source, String target, List<String> result) {
        List<String> middle = getSynonyms(source);
        if (middle == null || middle.size() == 0) {
            return result;
        }
        for (int i =0; i < middle.size(); i++) {
            if (!result.contains(middle.get(i))) {
                result.add(middle.get(i));
                if (middle.get(i) == target) {
                    return result;
                }
                else {
                    getMiddleChain (result.get(i), target, result);
                }
            }
        }
        return null;
    }

    public List<String> getShortestChain(String source, String target) {
        List<String> result = new ArrayList<>();
        result.add(source);
        result = getMiddleChain(source, target, result);
        System.out.println(result);
        return result;
    }

}
